import * as util from 'util'
import { parseString } from 'xml2js'

import request from './request'
import { md5 } from './crypto'
import { smsOptions } from '../config'

import * as debug from 'debug'
const log = debug('utils.sms')

class SMS {

  private readonly captchaMessage = `尊敬的用户：您的验证码是%s, 工作人员不会索取，请勿泄漏。如非本人操作，请忽略此短信。`
  private readonly fileKeyMessage = `尊敬的用户：您的作品文件解压密码是%s，请勿轻易向任何人泄漏。`

  private url: string
  private user: string
  private subcode: string
  private password: string
/* import { smsOptions } from '../config' 的内容：
  user: '61255',
  pass: 'dd61255',
  subcode: '2959',
  url: 'http://www.4001185185.com/sdk/smssdk!mt.action',
  /*

  constructor() {
    this.url = smsOptions.url
    this.user = smsOptions.user
    this.subcode = smsOptions.subcode
    this.password = md5(smsOptions.pass)
  }

  async sendCaptcha(phone: string, captcha: string) {
    if (phone && captcha) {
      const message: string = util.format(this.captchaMessage, captcha)
      return await this.send(phone, message)
    }

    return false
  }

  async send(phone: string, message: string) {
    log('Sms: %o', { phone, message })

    let sendResult: any = undefined
    try {
      const res = await request.get(
        this.url,
        {
          params: {
            sdk: this.user,
            code: this.password,
            pwdtype: 'md5',
            phones: phone,
            msg: message,
            encode: 'UTF-8',
            resulttype: 'xml',
            subcode: this.subcode
          }
        }
      )
      log('Sms Result: %o', res.data)

      parseString(res.data, function (err, result) {
        if (err) {
          sendResult = err
        } else {
          sendResult = result
        }
      })

    } catch (e) {
      if (e.code == 'ECONNABORTED') {
      } else {
        throw e
      }
    }

    return (sendResult && sendResult.result == '发送成功')
  }

}

export const sms = new SMS()
